package logic

import (
	"context"
	"time"
	"xialou_platform/app/tools"
	"xialou_platform/services/wallet/model"

	"xialou_platform/services/wallet/rpc/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type WalletInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWalletInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WalletInfoLogic {
	return &WalletInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 钱包信息
func (l *WalletInfoLogic) WalletInfo(in *walletClient.WalletInfoReq) (*walletClient.WalletInfoResp, error) {
	wallet, err := l.svcCtx.WalletModel.FindOneBySourceId(l.ctx, in.SourceId)
	if err != nil {
		if err == model.ErrNotFound {
			wallet = &model.Wallet{}
		} else {
			return nil, err
		}
	}
	today := tools.DateTimeToDate(time.Now())
	yesterday := today.AddDate(0, 0, -1)
	yesterdayEndTime := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 999, time.Local)

	todayProfit := l.svcCtx.WalletLogModel.FindProfit(l.ctx, in.SourceId, today, time.Now())
	yesterdayProfit := l.svcCtx.WalletLogModel.FindProfit(l.ctx, in.SourceId, yesterday, yesterdayEndTime)

	bankIcon, err := l.svcCtx.BankIconModel.FindOneByName(l.ctx, wallet.BankName)
	if err != nil {
		if err == model.ErrNotFound {
			bankIcon = &model.BankIcon{Icon: "https://imgs.ynz666.com/bank/icon/BANK.png"}
		} else {
			return nil, err
		}

	}

	return &walletClient.WalletInfoResp{
		Balance:         wallet.Balance,
		TodayProfit:     todayProfit,
		YesterdayProfit: yesterdayProfit,
		Icon:            bankIcon.Icon,
		BankName:        wallet.BankName,
		BankNumber:      wallet.BankNumber,
		SaleCardIncome:  wallet.SaleCardIncome,
		CouponIncome:    wallet.CouponIncome,
		AccountName:     wallet.AccountName,
	}, nil
}
